package com.hongkzh.www.conmon;

import com.jfinal.kit.PropKit;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 查看CK上传的图片
 * @author ThinkGem
 * @version 2014-06-25
 */
public class UserfilesDownloadServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * 上传文件基础虚拟路径
     */
    public static final String USERFILES_BASE_URL = "/userfiles/";

    public void fileOutputStream(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String filepath = req.getRequestURI();
        int index = filepath.indexOf(USERFILES_BASE_URL);
        if(index >= 0) {
            filepath = filepath.substring(index +USERFILES_BASE_URL.length());
        }
        try {
            filepath = decode(filepath, "UTF-8");
        } catch (UnsupportedEncodingException e1) {

        }
        File file = new File(PropKit.get("userfiles.basedir") + USERFILES_BASE_URL + filepath);
        try {
            copy(new FileInputStream(file), resp.getOutputStream());
            resp.setHeader("Content-Type", "application/octet-stream");
            return;
        } catch (FileNotFoundException e) {
            req.setAttribute("exception", new FileNotFoundException("请求的文件不存在"));
            req.getRequestDispatcher("/WEB-INF/views/error/404.jsp").forward(req, resp);
        }
    }

    public static int copy(InputStream in, OutputStream out) throws IOException {


        int var2;
        try {
            var2 =copy2(in, out);
        } finally {
            try {
                in.close();
            } catch (IOException var12) {
                ;
            }

            try {
                out.close();
            } catch (IOException var11) {
                ;
            }

        }

        return var2;
    }

    public static int copy2(InputStream in, OutputStream out) throws IOException {

        int byteCount = 0;
        byte[] buffer = new byte[4096];

        int bytesRead;
        for(boolean var4 = true; (bytesRead = in.read(buffer)) != -1; byteCount += bytesRead) {
            out.write(buffer, 0, bytesRead);
        }

        out.flush();
        return byteCount;
    }
    public static String decode(String source, String encoding) throws UnsupportedEncodingException {

        int length = source.length();
        ByteArrayOutputStream bos = new ByteArrayOutputStream(length);
        boolean changed = false;

        for(int i = 0; i < length; ++i) {
            int ch = source.charAt(i);
            if (ch == '%') {
                if (i + 2 >= length) {
                    throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\"");
                }

                char hex1 = source.charAt(i + 1);
                char hex2 = source.charAt(i + 2);
                int u = Character.digit(hex1, 16);
                int l = Character.digit(hex2, 16);
                if (u == -1 || l == -1) {
                    throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\"");
                }

                bos.write((char)((u << 4) + l));
                i += 2;
                changed = true;
            } else {
                bos.write(ch);
            }
        }

        return changed ? new String(bos.toByteArray(), encoding) : source;
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        fileOutputStream(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        fileOutputStream(req, resp);
    }
}